import 'dart:typed_data';

import 'package:dio/dio.dart';
import 'package:dragablegridview_flutter/dragablegridview_flutter.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/screen_util.dart';
import 'package:multi_image_picker2/multi_image_picker2.dart';
import 'package:provider/provider.dart';
import 'package:study_online/entity/Problem.dart';
import 'package:study_online/global/colors.dart';
import 'package:study_online/global/global.dart';
import 'package:study_online/pages/discussPage/DiscussViewModel.dart';
import 'package:flutter/material.dart';
import 'package:uuid/uuid.dart';
import '../DiscussModel.dart';
import 'ItemBin.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  const MyApp({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        //appBar: AppBar(
        //  backgroundColor: Colors.black26,
        //  title: Text('container'),
        //),
        body: PublishDiscussPage(couId: 1),
      ),
    );
  }
}

class PublishDiscussPage extends StatefulWidget {
  PublishDiscussPage({Key key, this.couId}) : super(key: key);
  int couId;

  @override
  _PublishDiscussPageState createState() {
    return _PublishDiscussPageState();
  }
}

class _PublishDiscussPageState extends State<PublishDiscussPage> {
  TextEditingController _controller;
  List<Asset> images = <Asset>[];
  List<ItemBin> itemBins = [];
  Widget _addIcon;
  var editSwitchController = EditSwitchController();

  @override
  void initState() {
    super.initState();
    _controller = new TextEditingController();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    ScreenUtil.init(
      BoxConstraints(
          maxWidth: MediaQuery.of(context).size.width,
          maxHeight: MediaQuery.of(context).size.height),
      designSize: Size(1080, 2340),
    );
    _addIcon = InkWell(
      onTap: () {
        setState(() {
          loadAssets();
        });
      },
      child: Container(
        width: (ScreenUtil().screenWidth -
                ScreenUtil().setWidth(10) * 6 -
                ScreenUtil().setWidth(110)) /
            3.0,
        height: (ScreenUtil().screenWidth -
                ScreenUtil().setWidth(10) * 6 -
                ScreenUtil().setWidth(110)) /
            3.0,
        color: Color(0xffF0F0F0),
        child: Icon(
          Icons.add,
          size: 50,
        ),
      ),
    );
    if (itemBins.isEmpty) itemBins.add(new ItemBin(_addIcon));
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        backgroundColor: Colors.white,
        leading: IconButton(
          icon: Icon(Icons.arrow_back, color: Colors.black),
          iconSize: ScreenUtil().setHeight(74),
          onPressed: () {
            Navigator.pop(context);
          },
        ),
        title: Text(
          '问题描述',
          style: TextStyle(
            fontSize: ScreenUtil().setSp(60),
            color: Colors.black,
          ),
        ),
        actions: [
          Container(
            padding: EdgeInsets.only(
                top: ScreenUtil().setHeight(40),
                bottom: ScreenUtil().setHeight(40)),
            width: ScreenUtil().setWidth(150),
            height: ScreenUtil().setHeight(60),
            child: RaisedButton(
              onPressed: () {
                print("###"+"uuu");
                String stuId = Global.getInstance().user.stuId;
                List<String> imgNames=[];
                for(int i=0;i<itemBins.length;++i){
                  Uuid uuid=new Uuid();
                  imgNames.add(uuid.v1()+".jpg");
                }
                Provider.of<PublishProblemViewModel>(context, listen: false)
                    .publishProblem(widget.couId, stuId, _controller.text,itemBins,imgNames);
              },
              color: AppColors.primary,
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.all(Radius.circular(8)),
              ),
              child: Text(
                '发表',
                style: TextStyle(
                  fontSize: ScreenUtil().setSp(36),
                  color: Colors.white,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),
          ),
          SizedBox(width: ScreenUtil().setWidth(50)),
        ],
      ),
      body: Container(
        margin: EdgeInsets.only(
            left: ScreenUtil().setWidth(55),
            right: ScreenUtil().setWidth(55),
            top: ScreenUtil().setHeight(110)),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              '请描述你的问题',
              style: TextStyle(
                fontSize: ScreenUtil().setSp(50),
                color: Colors.black,
                fontWeight: FontWeight.bold,
              ),
            ),
            SizedBox(height: ScreenUtil().setHeight(70)),
            Container(
              width: ScreenUtil().screenWidth - ScreenUtil().setWidth(110),
              height: ScreenUtil().setHeight(483),
              padding: EdgeInsets.all(ScreenUtil().setHeight(40)),
              decoration: BoxDecoration(
                color: AppColors.textBackground,
                borderRadius: BorderRadius.all(Radius.circular(10)),
              ),
              child: TextField(
                controller: _controller,
                maxLines: 8,
                decoration: InputDecoration.collapsed(
                    hintText: '问题开头输入#+内容,最后以空格结尾可以形成问题标签.',
                    hintStyle: TextStyle(
                      color: Color(0xffC3C3C3),
                    ),
                ),

              ),
            ),
            SizedBox(height: ScreenUtil().setHeight(70)),
            Expanded(
              child: DragAbleGridView(
                mainAxisSpacing: ScreenUtil().setHeight(10),
                crossAxisSpacing: ScreenUtil().setHeight(10),
                //childAspectRatio:1.8,
                crossAxisCount: 3,
                itemBins: itemBins,
                editSwitchController: editSwitchController,
                isOpenDragAble: true,
                animationDuration: 500,
                //milliseconds
                longPressDuration: 100,
                //milliseconds
                deleteIcon: Icon(
                  Icons.close,
                  color: Color(0xffF0F0F0),
                ),
                deleteIconClickListener: (int index) {
                  print(index);
                },
                child: (int position) {
                  //if(position!=itemBins.length-1) {
                  //  print("###" + itemBins[position].asset.name);
                  //}
                  return itemBins[position].data;
                },
                editChangeListener: () {
                  print("#1111");
                  changeActionState();
                },
              ),
            ),
          ],
        ),
      ),
    );
  }

  void changeActionState() {}


  Future<void> loadAssets() async {
    List<Asset> resultList = <Asset>[];
    try {
      resultList = await MultiImagePicker.pickImages(
        maxImages: 6,
        enableCamera: true,
        selectedAssets: images,
        cupertinoOptions: CupertinoOptions(
          takePhotoIcon: "chatPage",
          doneButtonTitle: "Fatto",
        ),
        materialOptions: MaterialOptions(
          //actionBarTitleColor: "#111111",
          actionBarColor: "#111111",
          actionBarTitle: "相册",
          allViewTitle: "All Photos",
          useDetailsView: false,
          selectCircleStrokeColor: "#000000",
        ),
      );
    } on Exception catch (e) {}
    if (!mounted) return;
    List<ItemBin> tmp = [];
    for (int i = 0; i < resultList.length; ++i)
      tmp.add(
          new ItemBin(_buildContainer(resultList[i]), asset: resultList[i]));
    tmp.add(new ItemBin(_addIcon));
    setState(() {
      images = resultList;
      itemBins = tmp;
    });
  }

  Widget _buildContainer(Asset asset) {
    return AssetThumb(
      asset: asset,
      width: (ScreenUtil().screenWidth -
              ScreenUtil().setWidth(10) * 6 -
              ScreenUtil().setWidth(110)) ~/
          3.0,
      height: (ScreenUtil().screenWidth -
              ScreenUtil().setWidth(10) * 6 -
              ScreenUtil().setWidth(110)) ~/
          3.0,
    );
  }
}
